import 'package:flip_card/flip_card_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/controller/knowledgeword.dart';
import 'package:ichinesereader/models/knowledgeword/knowledgeWord.dart';
import 'package:ichinesereader/pages/common/myWords.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/tools/strokAnimator.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flip_card/flip_card.dart';
import 'package:just_audio/just_audio.dart';
import 'package:ichinesereader/widgets/dialogs/createWordCardDialog.dart';
import '../../constants.dart';
import '../../controller/cache.dart';
import '../../themes/appTheme.dart';

class WordCard extends StatefulWidget {
  WordCard({Key? key, required this.flashcard}) : super(key: key);
  final KnowledgeWord flashcard;
  final KnowledgeWordsController _knowledgeWordsController = Get.find();

  @override
  WordCardState createState() => WordCardState();
}

class WordCardState extends State<WordCard> {
  AudioPlayer player = AudioPlayer();
  final FlipCardController flipController = FlipCardController();
  final box = Hive.box('appconfig');

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    player.dispose();
  }

  void flipCard() {
    flipController.toggleCard();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build WordCard widget');
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    var heading =
        widget.flashcard.text != null ? widget.flashcard.text.toString() : '';
    var subheading = widget.flashcard.pinyin != null
        ? widget.flashcard.pinyin.toString()
        : '';
    var supportingText = '';
    if (widget.flashcard.definition != null) {
      supportingText = widget.flashcard.definition.toString();
      supportingText = supportingText.replaceAll('[', '').replaceAll(']', '');
    }
    var folderId = widget.flashcard.folderId != null
        ? widget.flashcard.folderId.toString()
        : '';
    var teacherId = widget.flashcard.teacherId != null
        ? widget.flashcard.teacherId.toString()
        : '';
    var shared = new StringBuffer();
    if (widget.flashcard.shareStudents != null) {
      widget.flashcard.shareStudents!.forEach((element) {
        shared.write(element);
        shared.write('\n');
      });
    }

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Card(
          elevation: 6.0,
          color: Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
          clipBehavior: Clip.antiAlias,
          child: folderId == '' && teacherId == ''
              ? Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        IconButton(
                          color: Theme.of(context).primaryColor,
                          onPressed: () async {
                            if (widget.flashcard.audio != '') {
                              await player.setAudioSource(AudioSource.uri(
                                  Uri.parse(
                                      widget.flashcard.audio.toString())));
                              player.play();
                            } else {
                              Get.snackbar('Message'.tr,
                                  'please generate or record audio'.tr,
                                  backgroundColor: Get.theme.primaryColorDark,
                                  colorText: Get.theme.primaryColorLight,
                                  snackPosition: SnackPosition.BOTTOM);
                            }
                          },
                          icon: Icon(
                            Icons.audio_file,
                            color: Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Get.theme.primaryColor,
                          ),
                        ),
                        Visibility(
                            visible: isTeacher,
                            child: IconButton(
                              onPressed: () {
                                showGeneralDialog(
                                    context: context,
                                    transitionDuration:
                                        Duration(milliseconds: 400),
                                    pageBuilder: (bc, ania, anis) {
                                      return CreateWordCardDialog(
                                        title: 'Update Word Card'.tr,
                                        wordImageAddress: '',
                                        type: 'update',
                                        word: widget.flashcard,
                                      );
                                    });
                              },
                              icon: Icon(
                                Icons.update,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Get.theme.primaryColor,
                              ),
                            )),
                        if (shared.length > 0)
                          Tooltip(
                            message: shared.toString(),
                            child: IconButton(
                              // tooltip: shared.toString(),
                              color: Theme.of(context).primaryColor,
                              onPressed: () {},
                              icon: Icon(
                                Icons.share_rounded,
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Get.theme.primaryColor,
                              ),
                            ),
                          ),
                        IconButton(
                          color: Theme.of(context).primaryColor,
                          onPressed: () {
                            Get.to(() => StrokeAnimator(
                                  characters: widget.flashcard.text!.trim(),
                                ));
                          },
                          icon: Icon(
                            Icons.border_color,
                            color: Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Get.theme.primaryColor,
                          ),
                        ),
                        Checkbox(
                          activeColor: Get.isDarkMode
                              ? Colors.black
                              : Get.theme.primaryColor,
                          value: widget.flashcard.checked,
                          onChanged: (bool? value) {
                            setState(() {
                              widget.flashcard.checked = value;
                            });
                          },
                        ),
                      ],
                    ),
                    widget._knowledgeWordsController.obx((data) {
                      return FlipCard(
                        key: widget.flashcard.id != null &&
                                widget.flashcard.id != ''
                            ? Key(widget.flashcard.id.toString())
                            : UniqueKey(),
                        fill: Fill.fillBack,
                        controller: flipController,
                        direction: FlipDirection.VERTICAL,
                        speed: 1000,
                        onFlip: () async {
                          if (widget.flashcard.audio != null &&
                              widget.flashcard.audio != '') {
                            if (!disableWordCardAudioPlay) {
                              await player.setAudioSource(AudioSource.uri(
                                  Uri.parse(
                                      widget.flashcard.audio.toString())));
                              player.play();
                            }
                          }
                        },
                        back: Container(
                          margin: EdgeInsets.all(9.0),
                          child: Column(children: [
                            Expanded(
                              child: Container(
                                //margin: EdgeInsets.fromLTRB(6.0, 0.0, 6.0,6.0),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          heading,
                                          style: TextStyle(
                                              fontFamily: 'Noto Sans SC',
                                              color: Get.isDarkMode
                                                  ? Colors.white
                                                  : Colors.black,
                                              fontSize: 27.0),
                                        ),
                                        if (widget.flashcard.category != null)
                                          Padding(
                                            padding: const EdgeInsets.only(
                                                left: 9.0),
                                            child: Container(
                                              //词性//
                                              alignment: Alignment.topCenter,
                                              width: 42.0,
                                              margin:
                                                  EdgeInsets.only(left: 1.0),
                                              padding: EdgeInsets.symmetric(
                                                  horizontal: 2.0),
                                              decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          6.0),
                                                  //shape: BoxShape.circle,
                                                  color: Get.isDarkMode
                                                      ? Colors.blueGrey[100]
                                                      : AppTheme
                                                          .colors.lightPink),
                                              child: Text(
                                                widget.flashcard.category
                                                        .toString() +
                                                    '.',
                                                style: TextStyle(
                                                  fontFamily: 'Noto Sans SC',
                                                  fontSize: 12.0,
                                                  color: Colors.black,
                                                ),
                                              ),
                                            ),
                                          ),
                                      ],
                                    ),
                                    if (widget._knowledgeWordsController
                                        .ifPinyin.value)
                                      Text(
                                        //拼音//
                                        subheading,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: 'Noto Sans SC',
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorLight
                                                : Colors.grey),
                                      ),
                                  ],
                                ),
                              ),
                            ),
                            Expanded(
                                child: Container(
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    if (supportingText.length > 0)
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                          6.0,
                                          0.0,
                                          6.0,
                                          3.0,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.blueGrey,
                                          borderRadius:
                                              BorderRadius.circular(3.0),
                                        ),
                                        child: Text(
                                          // widget.flashcard.definition,
                                          supportingText,
                                          style: TextStyle(
                                              fontFamily: 'Noto Sans SC',
                                              fontSize: 12.0,
                                              color: Get.isDarkMode
                                                  ? Get.theme.primaryColorDark
                                                  : Colors.white),
                                        ),
                                      ),
                                    if (widget.flashcard.example != null &&
                                        widget.flashcard.example!.length > 0)
                                      Text(
                                        widget.flashcard.example.toString(),
                                        style: TextStyle(
                                            fontFamily: 'Noto Sans SC',
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Colors.blueGrey),
                                      ),
                                  ]),
                            ))
                          ]),
                        ),
                        front: Container(
                            width: 210,
                            height: 240,
                            child: SingleChildScrollView(
                              scrollDirection: Axis.vertical,
                              child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    if (widget
                                        ._knowledgeWordsController.ifWord.value)
                                      Padding(
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 18.0),
                                        //child: Flexible(
                                        child: Text(heading,
                                            style: TextStyle(
                                                color: Get.isDarkMode
                                                    ? Colors.white
                                                    : Colors.black,
                                                fontFamily: 'Noto Sans SC',
                                                fontSize: 30.0,
                                                overflow: TextOverflow.fade)),
                                        //),
                                      ),
                                    Visibility(
                                      visible: widget.flashcard.image != null &&
                                          widget.flashcard.image != '',
                                      child: Image.network(
                                        widget.flashcard.image.toString(),
                                        fit: BoxFit.cover,
                                        errorBuilder:
                                            (context, error, stackTrace) {
                                          return Image.asset(
                                              'assets/images/imagenotavailable.png',
                                              fit: BoxFit.cover);
                                        },
                                      ),
                                    ),
                                  ]),
                            )),
                      );
                    }),
                  ],
                )
              : Column(
                  children: [
                    ButtonBar(
                      buttonPadding: EdgeInsets.fromLTRB(0, 5, 5, 0),
                      children: [
                        Checkbox(
                          value: widget.flashcard.checked,
                          onChanged: (bool? value) {
                            setState(() {
                              widget.flashcard.checked = value;
                            });
                          },
                        ),
                        if (shared.length > 0)
                          Tooltip(
                              message: shared.toString(),
                              child: IconButton(
                                  // tooltip: shared.toString(),
                                  color: Get.isDarkMode
                                      ? AppTheme.colors.darkTheme2
                                      : Get.theme.primaryColor,
                                  onPressed: () {},
                                  icon: Icon(Icons.share_rounded))),
                      ],
                    ),
                    ListTile(
                        title: Text(
                          subheading,
                          textAlign: TextAlign.center,
                          style: Theme.of(context).textTheme.bodyLarge,
                        ),
                        subtitle: Text(
                          heading,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontFamily: 'Noto Sans SC',
                              color: Get.isDarkMode
                                  ? Get.theme.primaryColorDark
                                  : Colors.black),
                        ),
                        onTap: () {
                          if (!widget._knowledgeWordsController.mainMode.value)
                            return;
                          Log.debug('Folder tapped$folderId');
                          // _controller.createFolderKnowledgeWord();
                          if (folderId != '') {
                            widget._knowledgeWordsController.currdir
                                .add(folderId);
                            widget._knowledgeWordsController.currDirName
                                .add(heading);
                            widget._knowledgeWordsController
                                .fetchKnowledgeFolderTree(false);
                          } else if (teacherId != '') {
                            widget._knowledgeWordsController.currdir
                                .add(teacherId);
                            widget._knowledgeWordsController.currDirName
                                .add(heading);
                            widget._knowledgeWordsController
                                .fetchKnowledgeFolderTree(false);
                          }
                        }),
                    GestureDetector(
                      onTap: () {
                        if (!widget._knowledgeWordsController.mainMode.value)
                          return;
                        if (folderId != '') {
                          widget._knowledgeWordsController.currdir
                              .add(folderId);
                          widget._knowledgeWordsController.currDirName
                              .add(heading);
                          widget._knowledgeWordsController
                              .fetchKnowledgeFolderTree(false);
                        } else if (teacherId != '') {
                          widget._knowledgeWordsController.currdir
                              .add(teacherId);
                          widget._knowledgeWordsController.currDirName
                              .add(heading);
                          widget._knowledgeWordsController
                              .fetchKnowledgeFolderTree(false);
                        }
                      },
                      child: Container(
                        child: SvgPicture.asset('assets/images/folder.svg',
                            height: 120, width: 200),
                        // GFImageOverlay(
                        //   height: 120,
                        //   width: 200,
                        //   image: Image.asset('assets/images/folder.png').image,
                        //   boxFit: BoxFit.cover,
                        // ),
                      ),
                    ),
                  ],
                  // })
                )),
    );
  }
}
